package com.pzhu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pzhu.entity.Code;
import com.pzhu.entity.Online;
import com.pzhu.entity.Result;
import com.pzhu.service.OnlineService;
import org.apache.catalina.startup.Tomcat;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static java.time.ZoneId.systemDefault;

@RestController
@RequestMapping("api/online")
public class OnlineController {
    @Autowired
    private OnlineService onlineService;

    /**
     * 获取某月登陆人数和在线人数
     *
     * @param date
     * @return
     */
    @GetMapping
    public Result online(@Param("date") String date) {
        String[] split = date.split("-");
        LambdaQueryWrapper<Online> onlineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        onlineLambdaQueryWrapper.apply("year(date)={0}", split[0]);
        onlineLambdaQueryWrapper.apply("month(date)={0}", split[1]);
        List<Online> list = onlineService.list(onlineLambdaQueryWrapper);
        List<Integer> Logincount = new ArrayList<>(31);
        List<Integer> Onlinecount = new ArrayList<>(31);
        for (int i = 0; i < 31; i++) {
            Logincount.add(0);
            Onlinecount.add(0);
        }
        for (Online online : list) {
            // 将java.util.Date转换为java.time.LocalDate
            LocalDate localDate = online.getDate().toInstant().atZone(systemDefault()).toLocalDate();
            int day = localDate.getDayOfMonth();
            Logincount.set(day - 1, online.getLogincount());
            Onlinecount.set(day - 1, online.getOnlinecount());
        }
        List<List<Integer>> listresult = new ArrayList<>();
        listresult.add(Logincount);
        listresult.add(Onlinecount);
        return new Result(Code.success, "", listresult);
    }

    /**
     * 获取当天登陆人数和在线人数
     *
     * @return
     */
    @GetMapping("/today")
    public Result today() {
        QueryWrapper<Online> onlineQueryWrapper = new QueryWrapper<>();
        onlineQueryWrapper.between("date", LocalDate.now().atStartOfDay(), LocalDate.now().atTime(23, 59, 59));
        Online online = onlineService.getOne(onlineQueryWrapper);
        return new Result(Code.success, "", online);
    }

    @GetMapping("/count")
    public void count(HttpSession session,HttpServletResponse response) throws IOException {
    }
}